package cn.zysuyuan.item.aop;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author flypig
 * @version 1.0
 * @date 2019-11-15 13:43
 */

@Component
@Aspect
@Slf4j
public class PageHelperAspect {

    private Integer page;
    private Integer size;

    @Pointcut("execution(* cn.zysuyuan.item.service.impl.*.select*(java.util.Map<String,Object>))")
    public void pageFunction(){};

    @Around("pageFunction()")
    public Object serviceImplAop(ProceedingJoinPoint pjp){
        try {
            log.info("进入pagehelper aop....");

            //获取连接点方法运行时的入参列表
            Object[] args = pjp.getArgs();

            Map<String,Object> map = (Map<String,Object>)args[0];

            // 获取连接点的方法签名对象
            Signature signature = pjp.getSignature();

            // 获取连接点所在的类的对象（实例）
            Object target = pjp.getTarget();

            if (map.get("page") != null){
                this.page = Integer.parseInt((String) map.get("page"));
            }else{
                this.page = 1;
            }
            if (map.get("size") != null){
                this.size = Integer.parseInt((String) map.get("size"));
            }else{
                this.size = 5;
            }

            PageHelper.startPage(page,size);

            log.info("方法[{}]开始执行.....",signature.getName());
            // 调用业务成方法，执行sql语句
            Object object = pjp.proceed();
            log.info("方法[{}]执行结束....",signature.getName());
            return object;
        } catch (Throwable throwable) {
            log.info("pageInfo aop执行失败....");
            throw new RuntimeException(throwable);
        } finally {
            log.info("serviceImplAop执行结束.....");
        }
    }

}
